package com.happy3w.ssp.schoolmatehome.component.image;

import lombok.Getter;
import lombok.Setter;

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;

@Getter
@Setter
public class LinePrintContext implements AutoCloseable {
    private int width;
    private int rowHeight;
    private Font font;
    private Point location = new Point();

    private Graphics2D g2d;
    private FontMetrics  fontMetrics;

    public LinePrintContext width(int width) {
        this.width = width;
        return this;
    }

    public LinePrintContext rowHeight(int rowHeight) {
        this.rowHeight = rowHeight;
        return this;
    }

    public LinePrintContext font(Font font) {
        this.font = font;
        return this;
    }

    public LinePrintContext location(Point location) {
        this.location = location;
        return this;
    }

    public FontMetrics getFontMetrics() {
        if (fontMetrics != null) {
            return fontMetrics;
        }

        BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
        g2d = image.createGraphics();
        g2d.setFont(font);
        fontMetrics = g2d.getFontMetrics();

        return fontMetrics;
    }

    public void nextLine() {
        location = new Point(0, location.y + rowHeight);
    }

    public int leftWidth() {
        return width - location.x;
    }

    @Override
    public void close() throws Exception {
        if (g2d != null) {
            g2d.dispose();
            g2d = null;
        }
    }

    public LinePrintContext initStartLocation() {
        location = new Point(0, getFontMetrics().getHeight());
        return this;
    }
}
